'use client'
import {
   MenuFoldOutlined,
   HomeOutlined,
   PoweroffOutlined,
   MenuUnfoldOutlined,
   FileOutlined,
   DownOutlined,
   UserOutlined,
   BookOutlined,
} from '@ant-design/icons';
import { Layout, Menu, Tree, Dropdown, MenuProps, Button, message, Popconfirm, Input, Table, Select, Col, Row, Drawer } from 'antd';
import type { TableColumnsType, PopconfirmProps } from 'antd';
import React, { useState, ChangeEvent, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation'
import Link from 'next/link';
import type { TreeDataNode, TreeProps } from 'antd';

import TreeRight from './TreeRight';

import { getCookie } from '../utils'

interface favType {
   ttid: number,
   ttname: string
}
interface SelectItem {
   label: string,
   value: string;
}
const { Header, Sider, Content } = Layout;
const defaultData: TreeDataNode[] = [
   {
      title: '教育类',
      key: '0',
      children: [
         {
            title: '教育类1',
            key: '0-0',
         },
         {
            title: '教育类2',
            key: '0-1',
         },
      ],
   },
   {
      title: 'IT类',
      key: '1',
      children: [
         {
            title: 'IT类0',
            key: '1-0',
         },
         {
            title: 'IT类1',
            key: '1-1',
         },
      ],
   }
   
];

const confirm: PopconfirmProps['onConfirm'] = (e) => {
   message.success('Click on Yes');
};

const cancel: PopconfirmProps['onCancel'] = (e) => {
   console.log(e);
   message.error('Click on No');
};

const DocMgt: React.FC = () => {
   const [collapsed, setCollapsed] = useState(false);
   const [treecollapsed, setTreeCollapsed] = useState(false);
   const [showName, setShowName] = useState(false);
   const [iputVal, setIputVal] = useState('');
   const [showRenameBtn, setShowRenameBtn] = useState(false);
   const [showDelTypeBtn, setShowDelTypeBtn] = useState(false);
   const [rename, setRename] = useState('重命名该类别');
   const [selectedValue, setSelectedValue] = useState('');
   const [selectList, setSelectList] = useState<SelectItem[]>([])
   const [username, setUsername] = useState('');
   const [gData, setGData] = useState(defaultData);
   const [expandedKeys, setExpandKeys] = useState(['0-0']);
   const [open, setOpen] = useState(false);
   interface DataType {
      toid: number,
      tofrom: string;
      tohref: string;
      tolink: string;
      toname: string,
      totime: string;
   }

   const handleDelete = (id: number) => {
      fetch('/SWJDTXT/queryTodelete.action?toid=' + id, { method: 'POST' }).then(res => {
         res.text().then(datas => {
            if (datas == '成功') {
               message.success('删除成功');
               fetchTableData(selectedValue.split('-')[1])
            } else {
               message.error('删除失败！')
            }
         })
      })
   };
   const columns: TableColumnsType<DataType> = [
      {
         title: '文献名称',
         dataIndex: 'toname',
         key: 'toname',
         width: 300,
         fixed: 'left',
      },
      {
         title: '链接',
         width: 80,
         dataIndex: 'tolink',
         key: 'tolink',
         render: (_, record) => <a className='text-blue-500' target='_blank' href={record.tolink}>链接</a>,
      },
      {
         title: '文献来源',
         dataIndex: 'tohref',
         key: 'tohref',
         width: 150,
      },
      {
         title: '网站',
         dataIndex: 'tofrom',
         key: 'tofrom',
         width: 150,
      },
      {
         title: '收藏时间',
         dataIndex: 'totime',
         key: 'totime',
         width: 150,
      },
      {
         title: '操作',
         key: 'operation',
         fixed: 'right',
         width: 100,
         render: (_, record) => <Popconfirm
            title="删除提示"
            description="你确定要删除这个收藏吗?"
            onConfirm={() => handleDelete(record.toid)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
         >
            <Button type='primary' danger>删除</Button>
         </Popconfirm>,
      },
   ];
   const [data, setData] = useState<DataType[]>();
   useEffect(() => {
      let username = getCookie('sjhm');
      // if (username == '') {
      //    window.location.href="https://www.xsjxkt.com/qd/dl/login"
      //    message.warning('请首先登录！');
      //    return () => { }
      // }
      setUsername(username);
      async function fetchData() {
         // const response = await fetch('/SWJDTXT/queryTtpeo.action?ttpeople=13207192878', { method: 'POST' });
         const response = await fetch('/SWJDTXT/queryTtpeo.action?ttpeople=' + username, { method: 'POST' });
         const fetchedDatas = await response.json();
         let serverSelList = fetchedDatas.map((item: favType) => {
            return { label: item.ttname, value: item.ttid + '-' + item.ttname }
         })
         setSelectList(serverSelList)
      }
      fetchData();
      return () => {
         // 组件即将卸载，这里可以做一些清理工作，如取消请求等
      };
   }, []);
   const fetchTableData = (label: string) => {
      // 获取表格的数据
      // fetch('/SWJDTXT/queryTotype.action?toman=13207192878' + '&totype=' + label, { method: 'POST' }).then(res => {
      fetch('/SWJDTXT/queryTotype.action?toman=' + username + '&totype=' + label, { method: 'POST' }).then(res => {
         res.json().then(datas => {
            setData(datas)
         })
      })
   }
   const handleSelChange = (value: string) => {
      setSelectedValue(value)
      let label = value.split('-')[1]
      // 重命名start
      // 回归最初的状态
      setRename('重命名该类别')
      setShowName(false)
      // 设置默认值
      setIputVal(label)
      // 重命名end
      fetchTableData(label)
   };
   const handleRename = () => {
      if (rename == '重命名该类别') {
         setShowName(true)
         setRename('确定该名称')
         // 这里做异步的处理
      } else {
         setTimeout(() => {
            setRename('重命名该类别')
            setShowName(false)
         }, 3000)
      }
   }
   const changeInputVal = (event: ChangeEvent<HTMLInputElement>) => {
      setIputVal(event.target.value);
   };
   const handleDeleteSel = (id: number) => {
   }
   const router = useRouter()
   function onClick(obj: { key: string }) {
      if (obj.key === '1') {
         // 跳转到官网
      } else {
         // 退出登录
      }
   };
   const onClickMenu: MenuProps['onClick'] = e => {
      if (e.key == '11') {
         // 跳转到用户信息-我的信息页面
         router.push('/user')
      } else if (e.key == '31') {
         // 跳转到自定义数据集-数据集社区页面
         router.push('/dataClub')
      } else if (e.key == '32') {
         // 跳转到自定义数据集-已选数据集页面
         router.push('/dataChosen')
      }
   };
   const items = [{
      key: '1',
      label: (
         <Link href="https://www.xsjxkt.com">
            <HomeOutlined /><span style={{ marginLeft: 6 }}>回到官网</span>
         </Link>
      ),
   }, {
      key: '2',
      label: (
         <div><PoweroffOutlined /><span style={{ marginLeft: 6 }}>退出登录</span></div>
      ),
   }]
   const addChildNode = () => {

   }
   const addSiblings = () => {

   }
   const updateNode = () => {

   }
   const deleteNode = () => {

   }
   const handleSelect = (selectedKeys: any, info: any) => {
      console.log(selectedKeys, info);
      // const txt: string = info.selectedNodes[0]?.title
      // setTitle(txt)
      console.log(info.selectedNodes[0]?.title)
   };
   // 右键菜单点击事件，props里就是节点数据
   const handleItemClick = (type: any, item: any) => {
      console.log('右键菜单点击-key')
      console.log(type)
      console.log('右键菜单点击-item')
      console.log(item.props)
   };
   const showDrawer = () => {
      setOpen(true);
   };

   const onClose = () => {
      setOpen(false);
   };
   const treeRightMenu = {
      menuId: '1',
      items: [
         { key: 'add', name: '添加同级节点', handler: (props: any) => { handleItemClick('add', props) } },
         { key: 'edit', name: '修改此节点', handler: (props: any) => { handleItemClick('edit', props) } },
         { key: 'addSub', name: '添加子节点', handler: (props: any) => { handleItemClick('addSub', props) } },
         { key: 'del', name: '删除此节点', handler: (props: any) => { handleItemClick('del', props) } },
      ],
   };
   return (
      <Layout style={{ height: '100%' }}>
         <Sider style={{ backgroundColor: '#f5f5f5' }} trigger={null} collapsible collapsed={collapsed}>
            <div className="logo" />
            <Menu style={{ backgroundColor: '#f5f5f5', border: 'none' }}
               theme="light"
               onClick={onClickMenu}
               mode="inline"
               defaultOpenKeys={['2']}
               defaultSelectedKeys={['2']}
               items={[
                  // {
                  //    key: '1',
                  //    icon: <UserOutlined />,
                  //    label: '用户信息',
                  //    children: [
                  //       {
                  //          key: '11',
                  //          label: '我的信息',
                  //       },
                  //    ]
                  // },
                  {
                     key: '2',
                     icon: <BookOutlined />,
                     label: '文献管理',
                  },
                  {
                     key: '3',
                     icon: <FileOutlined />,
                     label: '自定义数据集',
                     children: [
                        {
                           key: '31',
                           label: '数据集社区',
                        },
                        {
                           key: '32',
                           label: '已选数据集',
                        }
                     ]
                  },
               ]}
            />
         </Sider>
         <Layout className="site-layout" style={{ backgroundColor: '#fff' }}>
            <Header className="site-layout-background" style={{ backgroundColor: '#f5f5f5', paddingLeft: 12 }}>
               {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                  className: 'trigger',
                  onClick: () => setCollapsed(!collapsed),
               })}
               <div style={{ float: 'right' }}>
                  <Dropdown menu={{ items, onClick }}>
                     <a onClick={e => e.preventDefault()}>
                        <UserOutlined /> {username}
                        <DownOutlined style={{ marginLeft: 8 }} />
                     </a>
                  </Dropdown>
               </div>
            </Header>
            <Content>
               <Layout style={{ height: '100%', background: '#fff' }}>
                  <Sider style={{ backgroundColor: '#fff' }} trigger={null} collapsible collapsed={treecollapsed}>
                     <div className="logo" />
                     <Row style={{ padding: 12, borderBottom: '2px solid #f5f5f5' }}>
                        <Col span={12} style={{ textAlign: 'center' }}><h2 style={{ fontWeight: 'bolder' }}>归档目录</h2></Col>
                        <Col span={12} style={{ textAlign: 'right' }}><Button size='small' type="primary" onClick={showDrawer}>目录管理</Button></Col>
                     </Row>
                     <Tree
                        showLine
                        defaultExpandAll
                        onSelect={handleSelect}
                        treeData={gData}
                     />
                  </Sider>
                  <Content style={{ backgroundColor: '#fff', borderLeft: '2px solid #f5f5f5', paddingTop: 6 }}>
                     <div style={{ marginBottom: 6 }}>
                        <Input style={{ display: 'inline-block', width: 240, marginLeft: 6 }} placeholder="文献名称" value={iputVal} onChange={changeInputVal} defaultValue="" />
                        <Button type="primary" style={{ marginLeft: 6 }} autoInsertSpace>
                           查询
                        </Button>
                     </div>
                     <Table
                        size="small"
                        columns={columns}
                        dataSource={data}
                        rowKey={(record) => record.toid}
                        scroll={{ x: 1500 }}
                        sticky={{ offsetHeader: 64 }}
                     />
                  </Content>
               </Layout>
            </Content>
         </Layout>
         <Drawer title="目录管理" onClose={onClose} open={open}>
            <TreeRight
               dataSource={gData}
               contextMenu={treeRightMenu}
               onSelect={handleSelect}
            />
         </Drawer>
      </Layout>
   );
};

export default DocMgt;